# motor 是一个异步 MongoDB 驱动，基于 asyncio。适合需要高并发处理的应用程序。
import motor

from common.singleton import Singleton
from config import MongoDbConfig, logger


class AsyncMongoDBConnection(Singleton):

    def __init__(self, host, port):
        # _init__ 是一个实例方法，在实例被创建后调用，用于初始化实例的属性。
        self.client = None
        self.host = host
        self.port = port
        self._initialize()

    def _initialize(self):
        self.client = motor.motor_tornado.MotorClient(self.host, self.port)

    def reconnect(self):
        """尝试重连到 MongoDB"""
        print("Attempting to reconnect to MongoDB...")
        try:
            # 重新创建客户端
            self.client.close()  # 关闭当前连接
            self.client = motor.motor_tornado.MotorClient(self.host, self.port)
            print("Reconnected successfully!")
        except Exception as e:
            print(f"Reconnect failed: {e}")

    def get_collection(self, collection_name=None, db_name='file_manage'):
        try:
            return self.client[db_name][collection_name]
        except Exception as e:
            logger.error(f"mongo error:{e}")
            self.reconnect()  # 尝试重连
        return self.client[db_name][collection_name]


mongodb_host = MongoDbConfig.host
mongodb_port = MongoDbConfig.port
mongo_connector = AsyncMongoDBConnection(mongodb_host, mongodb_port)
